package com.example.springbootdemo2023.bus.file.controller;


import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.example.springbootdemo2023.bus.file.dto.File;
import com.example.springbootdemo2023.bus.file.service.IFileService;
import com.example.springbootdemo2023.core.dto.MyResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * 文件存储
 * @author GaoJingBo
 * @since 2023-04-03
 */
@RestController
@RequestMapping("/file")
@Slf4j
@Api(tags = "文件上传、下载接口")
public class FileController {

    @Value("${springDemo.userFileSavePlace}")
    private String userFileSavePlace;

    @Resource(name = "fileServiceImpl")
    private IFileService fileService;


    @Autowired
    private FileStorageService fileStorageService;//注入实列

    /**
     * 单文件上传（非图片）
     * @param file
     * @return
     */
    @PostMapping("/uploadOneFile")
    @ApiOperation("单文件上传（非图片）")
    public FileInfo uploadPlatform(MultipartFile file) {
        log.debug("单文件上传（非图片）:"+file);
        return fileStorageService.of(file)
                .setPlatform(userFileSavePlace)    //使用指定的存储平台
                .upload();
    }

    /**
     * 多件上传（非图片）
     * @param files
     * @return
     */
    @PostMapping("/uploadMoreFile")
    @ApiOperation("多件上传（非图片）")
    public List<FileInfo> uploadMorePlatform(MultipartFile[] files) {
        log.debug("多件上传（非图片）:"+files.length);

        LinkedList<FileInfo> list = new LinkedList<>();
        for(MultipartFile file:files){
            FileInfo upload = fileStorageService.of(file)
                    .setPlatform(userFileSavePlace)    //使用指定的存储平台
                    .upload();
            list.addLast(upload);
        }
        return list;
    }

    /**
     * 单图片上传
     */
    @PostMapping("/uploadOneImage")
    @ApiOperation("单图片上传")
    public FileInfo uploadImage(MultipartFile file) {
        log.debug("单图片上传:"+file);
        return fileStorageService.of(file)
                .setPlatform(userFileSavePlace)
                .image(img -> img.size(1000,1000))  //将图片大小调整到 1000*1000
                .thumbnail(th -> th.size(200,200))  //再生成一张 200*200 的缩略图
                .upload();
    }

    /**
     * 多图片上传
     */
    @PostMapping("/uploadMoreImage")
    @ApiOperation("多图片上传")
    public List<FileInfo> uploadMoreImage(MultipartFile[] files) {
        log.debug("多图片上传:"+files.length);

        LinkedList<FileInfo> list = new LinkedList<>();
        for(MultipartFile file:files){
            FileInfo upload = fileStorageService.of(file)
                    .setPlatform(userFileSavePlace)
                    .image(img -> img.size(1000, 1000))  //将图片大小调整到 1000*1000
                    .thumbnail(th -> th.size(200, 200))  //再生成一张 200*200 的缩略图
                    .upload();

            list.addLast(upload);
        }

        return list;
    }

    @GetMapping("/getFileDataByFileID")
    @ApiOperation("获取图片所有信息-根据文件id")
    public MyResult getFileDataByFileID(String fileID){

        MyResult result = new MyResult();

        File byId = fileService.getById(fileID);
        result.setMsg("查询成功！");
        result.setData(byId);

        return result;
    }

    @GetMapping("/getThImageURLByFileID")
    @ApiOperation("获取图片缩略图URL-根据文件id")
    public String getThImageByFileID(String fileID){

        File byId = fileService.getById(fileID);

        return byId.getThUrl();
    }

    @GetMapping("/getImageURLByFileID")
    @ApiOperation("获取图片原图图URL-根据文件id")
    public String getImageByFileID(String fileID){

        File byId = fileService.getById(fileID);

        return byId.getUrl();
    }

    @GetMapping("/downloadImageThByFileID")
    @ApiOperation("下载图片缩略图-根据文件id")
    public void downloadImageThByFileID(String fileID, HttpServletResponse response){

        File byId = fileService.getById(fileID);

        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            log.warn("文件管理-缩略图下载异常");
            throw new RuntimeException(e);
        }

        fileStorageService.downloadTh(byId.getUrl()).outputStream(outputStream);
    }

    @GetMapping("/downloadByFileID")
    @ApiOperation("下载原文件-根据文件id")
    public void downloadImageByFileID(String fileID, HttpServletResponse response){

        File byId = fileService.getById(fileID);

        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            log.warn("文件管理-下载原文件异常");
            throw new RuntimeException(e);
        }

        fileStorageService.download(byId.getUrl()).outputStream(outputStream);
    }


}
